package com.caishi.lkx.aop;


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.UUID;

/**
 * 记录请求id
 * */
@Aspect
@Component
public class RequestLoggingAspect {

    private static final Logger logger = LoggerFactory.getLogger(RequestLoggingAspect.class);

    // 定义切点，拦截所有Controller中的方法
//    @Pointcut("execution(* com.caishi.lkx..api..*(..))")
//    public void controllerMethods() {}


    // 拦截所有Web请求
//    @Before("controllerMethods()")
    public void logExecutionTime(JoinPoint joinPoint) throws Throwable {
//        String className = joinPoint.getSignature().getDeclaringTypeName();
//        String methodName = joinPoint.getSignature().getName();
//        Object[] args = joinPoint.getArgs();

//        logger.info("开始执行: {}.{}", className, methodName);
//        logger.info("方法参数: {}", Arrays.toString(args));

        // 获取HTTP请求信息
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
//            logger.info("请求URL: {}", request.getRequestURL().toString());
//            logger.info("请求方法: {}", request.getMethod());
//            logger.info("客户端IP: {}", request.getRemoteAddr());
//            记录请求Id
            String requestId = request.getHeader("X-Request-ID");
            logger.info("请求Id: {}", requestId);
        }
    }
}

